﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;


public class StringPlus
{
    public static List<string> GetStrArray(string str, char speater, bool toLower)
    {
        List<string> list = new List<string>();
        string[] ss = str.Split(speater);
        foreach (string s in ss)
        {
            if (!string.IsNullOrEmpty(s) && s != speater.ToString())
            {
                string strVal = s;
                if (toLower)
                {
                    strVal = s.ToLower();
                }
                list.Add(strVal);
            }
        }
        return list;
    }
    public static string[] GetStrArray(string str)
    {
        return str.Split(new char[',']);
    }
    public static string GetArrayStr(List<string> list, string speater)
    {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < list.Count; i++)
        {
            if (i == list.Count - 1)
            {
                sb.Append(list[i]);
            }
            else
            {
                sb.Append(list[i]);
                sb.Append(speater);
            }
        }
        return sb.ToString();
    }

    #region 字符串在数组中的位置
    /// <summary>
    /// 字符串在数组中的位置
    /// </summary>
    /// <param name="A">数组</param>
    /// <param name="text">要查找的字符串</param>
    /// <returns>数组中的位置，从0开始，如果不存在返回-1</returns>
    public static int inAi(ArrayList A, string text)
    {
        int returnvalue = -1;
        if (A != null)
        {
            for (int i = 0; i < A.Count; i++)
            {
                if (DataTypePlus.requestString(A[i]).ToLower() == text.ToLower())
                {
                    returnvalue = i;
                    return i;
                }
            }
        }
        return returnvalue;
    }
    /// <summary>
    /// 字符串在数组中的位置
    /// </summary>
    /// <param name="A">数组</param>
    /// <param name="text">要查找的字符串</param>
    /// <returns>数组中的位置，从0开始，如果不存在返回-1</returns>
    public static int inAi(string[] A, string text)
    {
        int returnvalue = -1;
        if (A != null)
        {
            for (int i = 0; i < A.Length; i++)
            {
                if (DataTypePlus.requestString(A[i]).ToLower() == text.ToLower())
                {
                    returnvalue = i;
                    return i;
                }
            }
        }
        return returnvalue;
    }
    #endregion

    #region 根据字符串比对，返回不同结果
    /// <summary>
    /// 两字符串相同，则返回指定字符串，否则返回空串
    /// </summary>
    /// <param name="a_">要对比的字符串1</param>
    /// <param name="b_">要对比的字符串2</param>
    /// <param name="returnstr">如果前两字符串相同，则要返回的字符串</param>
    /// <returns></returns>
    public static string dengyu(string a_, string b_, string returnstr)
    {
        if (a_ == b_) return returnstr;
        else return "";
    }
    /// <summary>
    /// 两字符串相同，则返回指定字符串1，否则返回制定字符串2
    /// </summary>
    /// <param name="a_">要对比的字符串1</param>
    /// <param name="b_">要对比的字符串2</param>
    /// <param name="returnstr">要返回的指定字符串1</param>
    /// <param name="returnstr1">要返回的指定字符串2</param>
    /// <returns></returns>
    public static string dengyu(string a_, string b_, string returnstr, string returnstr1)
    {
        if (a_ == b_) return returnstr;
        else return returnstr1;
    }
    /// <summary>
    /// 字符串在数组中，则返回指定字符串1，否则返回制定字符串2
    /// </summary>
    /// <param name="a_">要查找的字符串</param>
    /// <param name="b_">用来着字符串的数组</param>
    /// <param name="returnstr">要返回的指定字符串1</param>
    /// <param name="returnstr1">要返回的指定字符串2</param>
    /// <returns></returns>
    public static string dengyuA(string a_, string[] b_, string returnstr, string returnstr1)
    {
        bool inA = false;
        foreach (string str_ in b_)
        {
            if (a_ == str_)
            {
                inA = true;
                return returnstr;
            }
        }
        if (!inA) return returnstr1;
        else return returnstr;
    }
    #endregion

    #region 删除最后一个字符之后的字符

    /// <summary>
    /// 删除最后结尾的一个逗号
    /// </summary>
    public static string DelLastComma(string str)
    {
        return str.Substring(0, str.LastIndexOf(","));
    }

    /// <summary>
    /// 删除最后结尾的指定字符后的字符
    /// </summary>
    public static string DelLastChar(string str, string strchar)
    {
        return str.Substring(0, str.LastIndexOf(strchar));
    }

    #endregion

    #region 全角半角转换
    /// <summary>
    /// 转全角的函数(SBC case)
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    public static string ToSBC(string input)
    {
        //半角转全角：
        char[] c = input.ToCharArray();
        for (int i = 0; i < c.Length; i++)
        {
            if (c[i] == 32)
            {
                c[i] = (char)12288;
                continue;
            }
            if (c[i] < 127)
                c[i] = (char)(c[i] + 65248);
        }
        return new string(c);
    }

    /// <summary>
    ///  转半角的函数(SBC case)
    /// </summary>
    /// <param name="input">输入</param>
    /// <returns></returns>
    public static string ToDBC(string input)
    {
        char[] c = input.ToCharArray();
        for (int i = 0; i < c.Length; i++)
        {
            if (c[i] == 12288)
            {
                c[i] = (char)32;
                continue;
            }
            if (c[i] > 65280 && c[i] < 65375)
                c[i] = (char)(c[i] - 65248);
        }
        return new string(c);
    }

    public static List<string> GetSubStringList(string o_str, char sepeater)
    {
        List<string> list = new List<string>();
        string[] ss = o_str.Split(sepeater);
        foreach (string s in ss)
        {
            if (!string.IsNullOrEmpty(s) && s != sepeater.ToString())
            {
                list.Add(s);
            }
        }
        return list;
    }
    #endregion

    #region 将字符串样式转换为纯字符串
    public static string GetCleanStyle(string StrList, string SplitString)
    {
        string RetrunValue = "";
        //如果为空，返回空值
        if (StrList == null)
        {
            RetrunValue = "";
        }
        else
        {
            //返回去掉分隔符
            string NewString = "";
            NewString = StrList.Replace(SplitString, "");
            RetrunValue = NewString;
        }
        return RetrunValue;
    }
    #endregion

    #region 将字符串转换为新样式
    public static string GetNewStyle(string StrList, string NewStyle, string SplitString, out string Error)
    {
        string ReturnValue = "";
        //如果输入空值，返回空，并给出错误提示
        if (StrList == null)
        {
            ReturnValue = "";
            Error = "请输入需要划分格式的字符串";
        }
        else
        {
            //检查传入的字符串长度和样式是否匹配,如果不匹配，则说明使用错误。给出错误信息并返回空值
            int strListLength = StrList.Length;
            int NewStyleLength = GetCleanStyle(NewStyle, SplitString).Length;
            if (strListLength != NewStyleLength)
            {
                ReturnValue = "";
                Error = "样式格式的长度与输入的字符长度不符，请重新输入";
            }
            else
            {
                //检查新样式中分隔符的位置
                string Lengstr = "";
                for (int i = 0; i < NewStyle.Length; i++)
                {
                    if (NewStyle.Substring(i, 1) == SplitString)
                    {
                        Lengstr = Lengstr + "," + i;
                    }
                }
                if (Lengstr != "")
                {
                    Lengstr = Lengstr.Substring(1);
                }
                //将分隔符放在新样式中的位置
                string[] str = Lengstr.Split(',');
                foreach (string bb in str)
                {
                    StrList = StrList.Insert(int.Parse(bb), SplitString);
                }
                //给出最后的结果
                ReturnValue = StrList;
                //因为是正常的输出，没有错误
                Error = "";
            }
        }
        return ReturnValue;
    }
    #endregion

    #region 去除HTML标记
    /// <summary>
    /// 去除HTML标记
    /// </summary>
    /// <param name="NoHTML">包括HTML的源码 </param>
    /// <returns>已经去除后的文字</returns>
    public static string NoHTML(string Htmlstring)
    {
        Htmlstring = HttpContext.Current.Server.HtmlDecode(Htmlstring).Trim();
        //删除脚本   
        Htmlstring = Regex.Replace(Htmlstring, @"<script[^>]*?>.*?</script>", "", RegexOptions.IgnoreCase);
        //删除HTML   
        Htmlstring = Regex.Replace(Htmlstring, @"<(.[^>]*)>", "", RegexOptions.IgnoreCase);
        Htmlstring = Regex.Replace(Htmlstring, @"([\r\n])[\s]+", "", RegexOptions.IgnoreCase);
        Htmlstring = Regex.Replace(Htmlstring, @"-->", "", RegexOptions.IgnoreCase);
        Htmlstring = Regex.Replace(Htmlstring, @"<!--.*", "", RegexOptions.IgnoreCase);

        Htmlstring = Regex.Replace(Htmlstring, @"&(quot|#34);", "\"", RegexOptions.IgnoreCase);
        Htmlstring = Regex.Replace(Htmlstring, @"&(amp|#38);", "&", RegexOptions.IgnoreCase);
        Htmlstring = Regex.Replace(Htmlstring, @"&(lt|#60);", "<", RegexOptions.IgnoreCase);
        Htmlstring = Regex.Replace(Htmlstring, @"&(gt|#62);", ">", RegexOptions.IgnoreCase);
        Htmlstring = Regex.Replace(Htmlstring, @"&(nbsp|#160);", "   ", RegexOptions.IgnoreCase);
        Htmlstring = Regex.Replace(Htmlstring, @"&(iexcl|#161);", "\xa1", RegexOptions.IgnoreCase);
        Htmlstring = Regex.Replace(Htmlstring, @"&(cent|#162);", "\xa2", RegexOptions.IgnoreCase);
        Htmlstring = Regex.Replace(Htmlstring, @"&(pound|#163);", "\xa3", RegexOptions.IgnoreCase);
        Htmlstring = Regex.Replace(Htmlstring, @"&(copy|#169);", "\xa9", RegexOptions.IgnoreCase);
        Htmlstring = Regex.Replace(Htmlstring, @"&#(\d+);", "", RegexOptions.IgnoreCase);

        Htmlstring.Replace("<", "");
        Htmlstring.Replace(">", "");
        Htmlstring.Replace("\r\n", "");
        Htmlstring = HttpContext.Current.Server.HtmlEncode(Htmlstring).Trim();

        return Htmlstring;
    }
    #endregion

    #region 显示钱数
    /// <summary>
    /// 显示钱数
    /// </summary>
    /// <param name="c"></param>
    /// <returns></returns>
    public static string showMoney(decimal c)
    {
        //return c.ToString("#0.00");
        string returnVal = String.Format("{0:C}", c);
        //returnVal = returnVal.Substring(0, returnVal.LastIndexOf(".00"));
        return returnVal;
    }
    public static string showMoney(object c)
    {
      return  showMoney( DataTypePlus.requestDecimal(c));
    }
    public static string showMoney(string c)
    {
        if (c == "") c = "0";
        return String.Format("{0:c}", Convert.ToDecimal(c));
    }
    public static string showCoin(object c)
    {
        decimal _coin = DataTypePlus.requestDecimal(c);
        return Decimal.Round(_coin, 2).ToString();
    }
    public static string showDateBrTime(object dt_)
    {
        return DataTypePlus.requestString(dt_).Replace(" ", "<br/>");
    }
    public static string showMoney_empty(object v_)
    {
        if (DataTypePlus.requestDecimal(v_) == 0) return "0";
        else return showMoney(v_);
    }
    #endregion

    #region MD5加密
    /// <summary>
    /// 转换到MD5
    /// </summary>
    /// <param name="str">加密前字符串</param>
    /// <param name="code">16位加密还是32位加密</param>
    /// <returns>加密后字符串</returns>
    public static string to_md5(string str, int code)
    {
        if (code == 16) //16位MD5加密（取32位加密的9~25字符） 
        {
            return System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(str, "MD5").ToLower().Substring(8, 16);
        }
        if (code == 32) //32位加密 
        {
            return System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(str, "MD5").ToLower();
        }
        return "00000000000000000000000000000000";
    }
    /// <summary>
    /// md5加密
    /// </summary>
    /// <param name="thisStr">需要加密的字符串</param>
    /// <returns>加密后的字符串</returns>
    public static string md5(string thisStr)
    {
        return to_md5(thisStr, 16);
    }
    #endregion

    /// <summary>
    /// 随机
    /// </summary>
    /// <returns></returns>
    public static int GetRandomSeed()
    {
        byte[] bytes = new byte[4];
        System.Security.Cryptography.RNGCryptoServiceProvider rng = new System.Security.Cryptography.RNGCryptoServiceProvider();
        rng.GetBytes(bytes);
        return BitConverter.ToInt32(bytes, 0);
    }
    /// <summary>
    /// 获取指定长度随机英文数字串号
    /// </summary>
    /// <param name="len">串号长度</param>
    /// <returns></returns>
    public static string GetRandomStr(int len)
    {
        string returnVal = "";
        string[] strA = { "1", "2", "3", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N" };
        for (int i = 0; i < len; i++)
        {
            Random rnd = new Random(StringPlus.GetRandomSeed());
            returnVal += strA[rnd.Next(0, strA.Length - 1)];
        }
        return returnVal;
    }
    /// <summary>
    /// 获取指定长度随机数字串号
    /// </summary>
    /// <param name="len">串号长度</param>
    /// <returns></returns>
    public static string GetRandomNum(int len)
    {
        string returnVal = "";
        string[] strA = { "0","1", "2", "3", "5", "6", "7", "8", "9"};
        for (int i = 0; i < len; i++)
        {
            Random rnd = new Random(StringPlus.GetRandomSeed());
            returnVal += strA[rnd.Next(0, strA.Length - 1)];
        }
        return returnVal;
    }
    /// <summary>
    /// convert the character to Asc code
    /// </summary>
    /// <param name="character"></param>
    /// <returns></returns>
    public static int Asc(string character)
    {
        if (character.Length == 1)
        {
            System.Text.ASCIIEncoding asciiEncoding = new System.Text.ASCIIEncoding();
            int intAsciiCode = (int)asciiEncoding.GetBytes(character)[0];
            return (intAsciiCode);
        }
        else
        {
            throw new Exception("Character is not valid.");
        }

    }
    /// <summary>
    /// convert the asc code to character
    /// </summary>
    /// <param name="asciiCode"></param>
    /// <returns></returns>
    public static string Chr(int asciiCode)
    {
        if (asciiCode >= 0 && asciiCode <= 255)
        {
            System.Text.ASCIIEncoding asciiEncoding = new System.Text.ASCIIEncoding();
            byte[] byteArray = new byte[] { (byte)asciiCode };
            string strCharacter = asciiEncoding.GetString(byteArray);
            return (strCharacter);
        }
        else
        {
            throw new Exception("ASCII Code is not valid.");
        }
    }

    public static string Object2Json(object object_)
    {
        Newtonsoft.Json.Converters.IsoDateTimeConverter timeConverter = new Newtonsoft.Json.Converters.IsoDateTimeConverter();
        timeConverter.DateTimeFormat = "yyyy'-'MM'-'dd' 'HH':'mm':'ss";
        return Newtonsoft.Json.JsonConvert.SerializeObject(object_, timeConverter);
    }
    /// <summary>
    /// Guid.Empte都replace成了“0”
    /// </summary>
    /// <param name="object_"></param>
    /// <returns></returns>
    public static string Object2Json4Js(object object_)
    {
        return Newtonsoft.Json.JsonConvert.SerializeObject(object_).Replace(Guid.Empty.ToString(), "0").Replace("2009-09-09 00:00:00", "").Replace("null", "\"\"");
    }

    public static string time2string(DateTime dt_)
    {
        string[] ABC = { "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N" };
        string returnVal = ABC[dt_.Year - 2013];
        returnVal += ABC[dt_.Month - 1];

        string Time = dt_.Day.ToString();
        Time += dt_.Hour.ToString();
        Time += dt_.Minute.ToString();
        Time += dt_.Second.ToString();

        returnVal += String.Format("{0:X}", Convert.ToInt64(Time));
        return returnVal;
    }
    /// <summary>
    /// 构造SQL语句 and 条件
    /// </summary>
    /// <param name="sql_">已构造的SQL</param>
    /// <param name="andSQL">要增加的条件（不含 ‘and’）</param>
    /// <returns></returns>
    public static string SQLand(string sql_, string andSQL)
    {
        string returnVal=sql_;
        if (andSQL != "")
        {
            if (returnVal != "") returnVal += " AND ";
            returnVal += andSQL;
        }
        return returnVal;
    }
    public static string GoodsStateStr(object state_,bool showNomal_){
        EnumHelper.GoodsState EnumState = (EnumHelper.GoodsState)state_;
        if (EnumState == EnumHelper.GoodsState.Nomal && !showNomal_) return "";
        else return EnumHelper.GetEnumDescription(EnumState);
    }
    public static string OrdersStateStr(object state_)
    {
        EnumHelper.OrdersState EnumState = (EnumHelper.OrdersState)state_;
        return EnumHelper.GetEnumDescription(EnumState);
    }
    public static string BuyDay2WeekName(int buyDay_)
    {
        switch (buyDay_)
        {
            case 0: return "天";
            case 1: return "一";
            case 2: return "二";
            case 3: return "三";
            case 4: return "四";
            case 5: return "五";
            case 6: return "六";
            default: return "";
        }
    }
    /// <summary>
    /// 获取指定长度字符串
    /// </summary>
    /// <param name="str_"></param>
    /// <param name="len_"></param>
    /// <returns></returns>
    public static string GetSubString(object str_, int len_)
    {
        string _str = DataTypePlus.requestString(str_);
        if (_str.Length <= len_) return _str;
        else return _str.Substring(0, len_);
    }
}

